package com.pi.pro.xcmg.am.was.web.cust.controller;

import com.alibaba.fastjson.JSONArray;
import com.pi.common.CodesConstants;
import com.pi.common.utils.StringUtils;
import com.pi.framework.core.controller.BaseCrudController;
import com.pi.framework.core.service.ICrudService;
import com.pi.framework.core.util.DateUtils;
import com.pi.framework.core.util.SecurityUtils;
import com.pi.framework.core.util.csv.CsvExporter;
import com.pi.framework.web.util.CsvView;
import com.pi.pro.xcmg.am.was.edi.infor.common.InforWasExchangeSupport;
import com.pi.pro.xcmg.am.was.edi.infor.common.InforWasXcmgExchangeConstants;
import com.pi.pro.xcmg.am.was.edi.infor.dto.reply.FuncReplyData;
import com.pi.pro.xcmg.am.was.edi.infor.dto.reply.TaskReportResultDto;
import com.pi.pro.xcmg.am.was.fac.service.WasCustomWorkService;
import com.pi.wms.common.WmsConstants;
import com.pi.wms.dto.base.LocationLineDto;
import com.pi.wms.entity.*;
import com.pi.wms.service.EdiTransactionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.datatables.mapping.DataTablesInput;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.*;


@Controller
@RequestMapping("/edi/transupload/ca")
public class CustApplyTransUnloadTransController extends BaseCrudController<TwiActTransList, Long> {

	@Autowired
	private EdiTransactionService service;
    @Autowired
    private WasCustomWorkService wasCustomWorkService;
	
	
	@Override
	protected ICrudService<TwiActTransList, Long> getCrudService() {
	    return service;
	}

	@Override
	protected String getPrefix() {
		return "transupload";
	}

	@Override
	protected TwiActTransList newModel(HttpServletRequest request) {
		return new TwiActTransList();
	}

	@Override
	protected void prepareDatatableConditions(Map<String, Object> query, DataTablesInput input) {
		super.prepareDatatableConditions(query, input);
	}

    @PostMapping("repostreq")
    public String repostReq(@RequestParam("ids") Long[] ids, Model model, HttpServletRequest request,
                          RedirectAttributes redirectAttributes) {
        model.addAttribute("params", getParams(request));
        TwiActTransList trans=null;
        if (ids != null && ids.length > 0) {
            String[] batchIds=new String[ids.length];
            int index=0;
            for (Long id : ids) {
                trans=service.findById(id);
                model.addAttribute("m", trans);
                model.addAttribute("ids", ids);
                model.addAttribute("batchIds", ids);
                batchIds[index++]=String.valueOf(id);
            }
            trans.setBatchIds(batchIds);
        }
        return this.view("transuploadrepost_form");
    }

    /**
    @PostMapping(value = { "repost", "repost/{id}" })
    public String repost(Model model, @Valid @ModelAttribute("m") TwiActTransList m, BindingResult result, HttpServletRequest request,
                            RedirectAttributes redirectAttributes) {
        model.addAttribute("params", getParams(request));

        System.out.println(m.getBatchIds());
        // 验证错误，则保持在编辑界面
        if (hasError(m, result)) {
            List<ObjectError> errors = result.getAllErrors();
            List<String> msgs = new ArrayList<String>();
            for (ObjectError err : errors) {
                msgs.add(err.getDefaultMessage());
            }
            super.addErrorMessage(model, msgs.toArray(new String[] {}));
            return edit(m, model, request, redirectAttributes);
        }
        //
        String notes=request.getParameter("notes");
        if ((m.getBatchIds() == null) || (m.getBatchIds().length==0)) {
            addSuccessMessage(redirectAttributes, "重传成功");
            return this.redirect("");
        }
        Long tid=null;
        TwtActTransList tran=null;
        List<Long> tids=new ArrayList<>();
        List<FuncReplyData<TaskReportResultDto>> resultDatas=null;
        String mr="";
        String mall="";
        try{
            for (String bid:m.getBatchIds()){
                if (StringUtils.isNullOrBlank(bid)){
                    continue;
                }
                tid=StringUtils.getLongValue(bid);
                if (tid==null){
                    continue;
                }
                tids.add(tid);
            }
            resultDatas=this.wasCustomWorkService.handleWasEdiTransDataToXwms(tids, true, notes, SecurityUtils.getLoginUsername());
            for (FuncReplyData<TaskReportResultDto> d : resultDatas) {
                if (d==null){
                    continue;
                }
                mr= InforWasExchangeSupport.errorMessage(d);
                if (!StringUtils.isNullOrBlank(mr)){
                    mall=mall+mr+"\nr";
                }
            }
            if(!StringUtils.isNullOrBlank(mall)){
                addErrorMessage(redirectAttributes, "重传失败"+m);
                return this.redirect("");
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        //
        addSuccessMessage(redirectAttributes, "重传成功");
        return this.redirect("");
    }
    **/

    @PostMapping("repost")
    public String repost(@RequestParam("ids") Long[] ids, Model model, HttpServletRequest request,
                         RedirectAttributes redirectAttributes) {
        model.addAttribute("params", getParams(request));
        String m="";
        String mr="";
        TwtActTransList tran=null;
        if ((ids == null) || (ids.length==0)) {
            addSuccessMessage(redirectAttributes, "重传成功");
            return this.redirect("");
        }
        List<FuncReplyData<TaskReportResultDto>> resultDatas=this.wasCustomWorkService.handleWasEdiTransDataToXwms(Arrays.asList(ids),   true, null, SecurityUtils.getLoginUsername());
        for (FuncReplyData<TaskReportResultDto> d : resultDatas) {
            if (d==null){
                continue;
            }
            mr= InforWasExchangeSupport.errorMessage(d);
            if (!StringUtils.isNullOrBlank(mr)){
                m=m+mr+"\nr";
            }
        }
        if(!StringUtils.isNullOrBlank(m)){
            addErrorMessage(redirectAttributes, "重传失败"+m);
            return this.redirect("");
        }
        addSuccessMessage(redirectAttributes, "重传成功");
        return this.redirect("");
    }

    @PostMapping("closereq")
    public String closeReq(@RequestParam("ids") Long[] ids, Model model, HttpServletRequest request,
                           RedirectAttributes redirectAttributes) {
        model.addAttribute("params", getParams(request));
        TwiActTransList trans=null;
        if (ids != null && ids.length > 0) {
            String[] batchIds=new String[ids.length];
            int index=0;
            for (Long id : ids) {
                trans=service.findById(id);
                model.addAttribute("m", trans);
                model.addAttribute("ids", ids);
                model.addAttribute("batchIds", ids);
                batchIds[index++]=String.valueOf(id);
            }
            trans.setBatchIds(batchIds);
        }
        return this.view("transuploadclose_form");
    }

    //
    @PostMapping(value = { "close", "close/{id}" })
    public String close(Model model, @Valid @ModelAttribute("m") TwiActTransList m, BindingResult result, HttpServletRequest request,
                         RedirectAttributes redirectAttributes) {
        model.addAttribute("params", getParams(request));

        System.out.println(m.getBatchIds());
        // 验证错误，则保持在编辑界面
        if (hasError(m, result)) {
            List<ObjectError> errors = result.getAllErrors();
            List<String> msgs = new ArrayList<String>();
            for (ObjectError err : errors) {
                msgs.add(err.getDefaultMessage());
            }
            super.addErrorMessage(model, msgs.toArray(new String[] {}));
            return edit(m, model, request, redirectAttributes);
        }
        //
        String notes=request.getParameter("notes");
        if ((m.getBatchIds() == null) || (m.getBatchIds().length==0)) {
            addSuccessMessage(redirectAttributes, "标记成功");
            return this.redirect("");
        }
        Long tid=null;
        TwiActTransList tran=null;
        String info=null;
        try{
            for (String bid:m.getBatchIds()){
                if (StringUtils.isNullOrBlank(bid)){
                    continue;
                }
                tid=StringUtils.getLongValue(bid);
                if (tid==null){
                    continue;
                }
                tran=this.service.findById(tid);
                if (tran==null){
                    continue;
                }
                if (CodesConstants.COMMON_STATUS_CLOSED.equalsIgnoreCase(tran.getEdiReceiveStatus())){
                    continue;
                }
                info=null;
                if (!StringUtils.isNullOrBlank(notes)){
                    info=notes;
                    /**
                    if (!StringUtils.isNullOrBlank(tran.getNotes())){
                        info=tran.getNotes()+"//" + notes;
                    }
                     **/
                    tran.setNotes(info);
                }
                tran.setEdiReceiveStatus(CodesConstants.COMMON_STATUS_CLOSED);
                tran.setLastModifiedDate(new Date());
                tran.setLastModifiedBy(SecurityUtils.getLoginUsername());
                this.service.save(tran);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        //
        addSuccessMessage(redirectAttributes, "标记成功");
        return this.redirect("");
    }

	//
	@PostMapping("close")
	public String close(@RequestParam("ids") Long[] ids, Model model, HttpServletRequest request,
						 RedirectAttributes redirectAttributes) {
		model.addAttribute("params", getParams(request));
		String m="";
		String mr="";
		TwtActTransList tran=null;
		if ((ids == null) || (ids.length==0)) {
			addSuccessMessage(redirectAttributes, "标记成功");
			return this.redirect("");
		}
        String notes=request.getParameter("notes");
        TwiActTransList t=null;
		String worker=null;
		String info=null;
		try{
            worker=SecurityUtils.getLoginUsername();

		    for (Long id:ids){
		        if (id==null){
		            continue;
                }
                t=this.service.findById(id);
		        if (t==null){
		            continue;
                }
                if (CodesConstants.COMMON_STATUS_CLOSED.equalsIgnoreCase(t.getEdiReceiveStatus())){
		            continue;
                }
                info=null;
                if (!StringUtils.isNullOrBlank(notes)){
                    if (!StringUtils.isNullOrBlank(t.getNotes())){
                        info=t.getNotes()+"//" + notes;
                    }else {
                        info=notes;
                    }
                    t.setNotes(info);
                }
                t.setEdiReceiveStatus(CodesConstants.COMMON_STATUS_CLOSED);
                t.setLastModifiedDate(new Date());
                t.setLastModifiedBy(worker);
                this.service.save(t);
            }
        }catch (Exception e){
		    m="标记完成状态出错.异常:"+e.getMessage();
            e.printStackTrace();
        }
		if(!StringUtils.isNullOrBlank(m)){
			addErrorMessage(redirectAttributes, "标记失败"+m);
			return this.redirect("");
		}
		addSuccessMessage(redirectAttributes, "标记成功");
		return this.redirect("");
	}

	@PostMapping(value = { "/export" })
	public ModelAndView export(@RequestParam Map<String, Object> query, DataTablesInput input) {
		query.put("type", WmsConstants.TRANS_TYPE_SHIP);
		String inputParams = "";
		if (query.get("input")!=null){
			inputParams=query.get("input").toString();
		}
		if (StringUtils.isNotEmpty(inputParams)) {
			input = JSONArray.parseObject(inputParams, DataTablesInput.class);
		}
		input.setLength(-1);
		String ymd = DateUtils.format(new Date(), DateUtils.FORMAT_DATE_YYYY_MM_DD_HHMMSS);
		final DataTablesInput ins = input;
		Map<Long,TwmBasMaterial> materials=new HashMap<>();
		Map<Long,TwaInventoryLotattr> lotattrs=new HashMap<>();
		CsvExporter<TwiActTransList> exporter = new CsvExporter<TwiActTransList>() {
			@Override
			public String[] header() {
				return "创建时间,交易类型,物料编码,物料名称,WBS,供应商,数量,业务类型,任务号,WMS批,单号,上传状态,反馈信息"
						.split(",");
			}

			@Override
			public Collection<TwiActTransList> nextList(int pageSize, int page) {
				ins.setLength(pageSize);
				ins.setStart(page * pageSize);
				Pageable pageable = PageRequest.of(page, pageSize);
				Page<TwiActTransList> out = service.findAll(query,pageable);
				return out == null ? null : out.getContent();
			}

			@Override
			public Collection<String> toText(TwiActTransList d) {
				List<String> item = new ArrayList<String>();

				item.add(DateUtils.format(d.getCreatedDate(), DateUtils.FORMAT_DATE_YYYY_MM_DD_HH_MM_SS));
				if (WmsConstants.TRANS_TYPE_RECEIVE.equalsIgnoreCase(d.getTransType())){
				    item.add("收");
                }else if (WmsConstants.TRANS_TYPE_SHIP.equalsIgnoreCase(d.getTransType())){
                    item.add("发");
                }else {
                    item.add(StringUtils.ifNullOrBlank(d.getTransType(), ""));
                }
                item.add(d.getMaterialCode());
                item.add(d.getMaterialName());
                item.add(StringUtils.ifNullOrBlank(d.getUdf03(), ""));
                item.add(StringUtils.ifNullOrBlank(d.getSupplierCode(), ""));
                if (d.getQtyTrans()==null){
                    item.add("");
                }else {
                    item.add(d.getQtyTrans().stripTrailingZeros().toPlainString());
                }
                if (InforWasXcmgExchangeConstants.TASK_TYPE_PUTAWAY.equalsIgnoreCase(d.getUdf16())){
                    item.add("上架");
                }else if (InforWasXcmgExchangeConstants.TASK_TYPE_PICK.equalsIgnoreCase(d.getUdf16())){
                    item.add("发货");
                }else if (InforWasXcmgExchangeConstants.TASK_TYPE_MOVE.equalsIgnoreCase(d.getUdf16())){
                    item.add("移库");
                }else {
                    item.add(StringUtils.ifNullOrBlank(d.getUdf16(), ""));
                }
                item.add(StringUtils.ifNullOrBlank(d.getRefTaskNumber(), ""));
                item.add(StringUtils.ifNullOrBlank(d.getUdf17(), ""));
                item.add(StringUtils.ifNullOrBlank(d.getDocumentNumber(), ""));
                if (CodesConstants.COMMON_STATUS_CLOSED.equalsIgnoreCase(d.getEdiReceiveStatus())){
                    item.add("完成");
                }else if (CodesConstants.COMMON_STATUS_CANCELLED.equalsIgnoreCase(d.getEdiReceiveStatus())){
                    item.add("取消");
                }else if (CodesConstants.COMMON_STATUS_APP_ERROR.equalsIgnoreCase(d.getEdiReceiveStatus())){
                    item.add("异常");
                }else {
                    item.add("完成");
                }
                item.add(StringUtils.ifNullOrBlank(d.getEdiReceiveMessage(), ""));
				return item;
			}
		};
		return new ModelAndView(new CsvView(exporter, "upload_trans_list_" + ymd));
	}



	protected String redirect(String relativeUrl) {
		if(!com.pi.framework.core.util.StringUtils.isNullOrBlank(relativeUrl) && !relativeUrl.startsWith("/")) {
			relativeUrl = "/" + relativeUrl;
		}
		return "redirect:" + this.referUrl() + relativeUrl;
	}

	protected String root(String relativeUrl) {
		if(!com.pi.framework.core.util.StringUtils.isNullOrBlank(relativeUrl) && !relativeUrl.startsWith("/")) {
			relativeUrl = "/" + relativeUrl;
		}
		return this.referUrl() + relativeUrl;
	}


	private String referUrl(){
		return "/edi/transupload/";
	}

}
